<?php
namespace app\appapi\controller;
use think\Controller;
use think\Request;
use think\Db;
use app\appapi\WeShare;
use aliyun\oss\ossValidate;
use aliyun\oss\ossBase;
use aliyun\oss\OssClient;
class Common extends Controller
{
    var $WxApp_User_Id;
    var $REQUEST;
    function _initialize(){
        judgeFilterSql();
        $this->REQUEST = Request::instance();
        $this->appCheckLogin();
    }
    public function appCheckLogin($value='')
    {
        $uid = cache('we_user_id');
        if(Db::name('user')->where(array('User_id'=>$uid))->value('User_id')){
            $this->WxApp_User_Id = $uid;
        }else{
            $this->WxApp_User_Id = '';
        }
    }
    //上传oss文件
   public function putObject($bucket='', $object='', $content)
   {
	   $ossConfig = getWxconfig('aliyunOss');
	   $bucket = $bucket?$bucket:$ossConfig['Bucket'];
	   $object = $object?$object:sha1(date('YmdHis', time()) . uniqid()) . '.png';
	   try{
			$ossClient = new OssClient($ossConfig['KeyId'],$ossConfig['KeySecret'],$ossConfig['Endpoint'],true);
			return json($result = $ossClient->putObject($bucket, $object, $content));
		} catch(OssException $e) {
			printf(__FUNCTION__ . ": FAILED\n");
			printf($e->getMessage() . "\n");
			return;
		}
   }
    /* 刪除oss文件*/
   public function deleteOssFile($object,$bucket=''){				   
		try{
            $ossConfig = getWxconfig('aliyunOss');
            if(get_headers($object)){
                $object = str_replace($ossConfig['Endpoint'],'',$object);
            }
            $bucket = $bucket?$bucket:$ossConfig['Bucket'];
			$OssClient = new OssClient($ossConfig['KeyId'],$ossConfig['KeySecret'],$ossConfig['Endpoint'],true);
			  if(is_array($object)){
				  if($OssClient->deleteObjects($bucket,$object));
				  return json(['error'=>1001,'msg'=>'删除成功']);
			  }else{
			  	if($OssClient->deleteObject($bucket,$object)['info']['http_code']==204) 
				return json(['error'=>1001,'msg'=>'删除成功']);
			  }
			  return json(['error'=>1002,'msg'=>'删除失败']);
		} catch(OssException $e) {
			// printf(__FUNCTION__ . ": FAILED\n");
			// printf($e->getMessage() . "\n");
			return false;
		}
   }
   //获取微信Token
   public function getWxAppToken($appid='',$serect='',$weapp='')
   {
        if(!$access_token = cache('access_token')){
            if(!$weapp) $weapp = new WeShare(); 
            if(!$appid || !$serect){
                $wAppconfig = getWxconfig('weAppSystem');
                $apid = $wAppconfig['app_id'];
                $serect = $wAppconfig['secret'];
            }
            $getArr = array();
            $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$serect;
            $result = json_decode($weapp->wxNetworkRequest($url,$getArr,"GET"));
            $access_token = $result->access_token;
            cache('access_token',$access_token,3600*2);
        }
        return $access_token;
   }
}

